var datalist = []
var datalist2 = []
$().ready(function () {
    validateRule();
    changes()
});

$(function () {
    getAreaTree();
});

$(() => {
    $('#quiz1').change(() => {
        let quiz1 = $('#quiz1').val()
        $("#quiz2").empty()
        $("#quiz3").empty()
        let cityList2 = datalist.find((item) => item.value == quiz1).childrenList
        datalist2 = datalist.find((item) => item.value == quiz1).childrenList
        $("#quiz2").append("<option value=''>请选择</option>");
        for (let key in cityList2) {
            var a = cityList2[key]
            $("#quiz2").append("<option value='" + a.value + "'>" + a.value + "</option>");
        }

    })
    $('#quiz2').change(() => {
        let quiz2 = $('#quiz2').val()
        if ($("#quiz3").val()) {
            $("#quiz3").empty()
        }
        let cityList3 = datalist2.find((item) => item.value == quiz2).childrenList
        $("#quiz3").append("<option value=''>请选择</option>");
        for (let key in cityList3) {
            var a = cityList3[key]
            $("#quiz3").append("<option value='" + a.value + "'>" + a.value + "</option>");
        }
        // console.log(quiz2)
        // $('#quiz2').val(quiz2)
    })
});

function getCheckedRoles() {
    var adIds = "";
    $("input:checkbox[name=role]:checked").each(function (i) {
        if (0 == i) {
            adIds = $(this).val();
        } else {
            adIds += ("," + $(this).val());
        }
    });
    return adIds;
}

function save() {

    // if( !$("#userType").val() ){
    // 	layer.msg('请选择用户类型');
    // 	return false;
    // }
    if (!$("#username").val()) {
        layer.msg('请输入用户姓名');
        return false;
    }
    if (!$("#mobile").val()) {
        layer.msg('请输入电话号码');
        return false;
    }
    if (!$("#password").val()) {
        layer.msg('请输入密码');
        return false;
    }
    if (!$("#passwords").val()) {
        layer.msg('请确认密码');
        return false;
    }
    if ($("#password").val() !== $('#passwords').val()) {
        layer.msg('两次密码不一致');
        return false;
    }

    $("#roleIds").val(getCheckedRoles());
    $.ajax({
        cache: true,
        type: "POST",
        url: "/sys/user/fromSave",
        data: $('#signupForm').serialize(),// 你的formid
        async: false,
        error: function (request) {
            parent.layer.alert("Connection error");
        },
        success: function (data) {
            if (data.data) {
                handleIsConfirm(JSON.stringify(data.data))
                return false;
            }
            if (data.code == 0) {
                parent.layer.msg("操作成功");
                parent.reLoad();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);

            } else {
                parent.layer.alert(data.msg)
            }

        }
    });

}

function getUserTypeDesc(type) {
    switch (type) {
        case '0':
            return '学生';
        case '1':
            return '老师';
        case '2':
            return '讲师';
        default:
            return '未知类型';
    }
}

function handleIsConfirm(data) {
    var confirmMsg = `<div style="color: #409EFF;font-weight: bold">该用户已存在，是否添加为资源库用户？</div>
    <div style="color: #409EFF;font-weight: bold">用户名: ${JSON.parse(data).username}</div>
    <div style="color: #409EFF;font-weight: bold">姓名: ${JSON.parse(data).name?JSON.parse(data).name:'暂无'}</div>
    <div style="color: #409EFF;font-weight: bold">手机号: ${JSON.parse(data).mobile}</div>
    <div style="color: #409EFF;font-weight: bold">用户类型: ${getUserTypeDesc(JSON.parse(data).type)}</div>
`;
    layer.confirm(confirmMsg, {
        title: `提示`,
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: "/sys/user/transformUser",
            type: "post",
            data: JSON.parse(data),
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    parent.reLoad();
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);
                } else {
                    layer.msg(r.msg);
                }
            }
        }), function () {
            // 点击取消按钮后的回调函数
            console.log("用户点击了取消");
            // 这里可以写取消后的处理逻辑，如果有的话
            // 关闭confirm对话框
            layer.close(index);
        }
    })
}

// 获取地址
function getAreaTree() {
    $.ajax({
        cache: true,
        type: "GET",
        url: "/secretKey/getAreaTree",
        async: false,
        error: function (request) {
            parent.layer.alert("Connection error");
        },
        success: function (data) {
            datalist = data.data
            if (data.data.length == 0) {
                $("#quiz1").append('<option value="">暂无数据</option>');
            } else {
                $("#quiz1").append('<option value="">请选择</option>');
                for (let key in data.data) {
                    var a = data.data[key]
                    $("#quiz1").append("<option value='" + a.value + "'>" + a.value + "</option>");
                }

            }

        }
    });

}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            name: {
                required: true
            },
            username: {
                required: true,
            },
            password: {
                required: true,
                minlength: 6,
                maxlength: 8,
            },
            type: {
                required: true
            },
            passwords: {
                required: true,
                minlength: 6,
                maxlength: 8,
                equalTo: "#password"
            },
            email: {
                // required : true,
                email: true
            },
            mobile: {
                isPhone: true,
                required: true,
                // remote: {
                //     url: "/sys/user/exist", // 后台处理程序
                //     type: "post", // 数据发送方式
                //     dataType: "json", // 接受数据格式
                //     data: { // 要传递的数据
                //         mobile: function () {
                //             return $("#mobile").val();
                //         }
                //     }
                // }
            },
            topic: {
                required: "#newsletter:checked",
                minlength: 2
            },
            agree: "required"
        },
        messages: {

            name: {
                required: icon + "请输入姓名"
            },
            username: {
                required: icon + "请输入您的用户姓名",
                minlength: icon + "用户名必须两个字符以上",
            },
            password: {
                required: icon + "请输入您的密码",
                minlength: icon + "密码必须6个字符以上",
                maxlength: icon + '密码只能8个字符'
            },
            passwords: {
                required: icon + "请再次输入密码",
                minlength: icon + "密码必须6个字符以上",
                equalTo: icon + "两次输入的密码不一致"
            },
            mobile: {
                required: icon + "请输入电话号码",
                remote: icon + "电话号码已经存在"
            }
        }
    })
}

var openDept = function () {
    layer.open({
        type: 2,
        title: "选择部门",
        area: ['300px', '450px'],
        content: "/sys/dept/treeView"
    })
}

function loadDept(deptId, deptName) {
    $("#deptId").val(deptId);
    $("#deptName").val(deptName);
}


const changes = () => {
    $("#userType").change(function (ev) {
        if (ev.target.value == 0) {
            $("#insertion").html(`
			<div class="student">
			  <div class="form-group">
				<label class="col-sm-3 control-label">学历：</label>
				<div class="col-sm-8">
		
				  <select class="form-control valid" id="school_education"  name="education">
					<option value="0">请选择</option>
					<option value="1">本科</option>
					<option value="2">专科</option>
				  </select>
		
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">入学时间：</label>
				<div class="col-sm-8">
				  <input id="timeOfEnrollment" name="timeOfEnrollment" class="form-control" type="text">
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">学校名称：</label>
				<div class="col-sm-8">
				  <input id="school" name="school" class="form-control" type="text">
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">所学专业：</label>
				<div class="col-sm-8">
				  <input id="school_major" name="major" class="form-control" type="text">
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">学校所在地：</label>
				<div class="col-sm-8">
				  <input id="schoolAddressOne" name="schoolAddress" class="form-control" type="text">
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">学校详细地址：</label>
				<div class="col-sm-8">
				  <input id="schoolIndetailAddressOne" name="schoolIndetailAddress" class="form-control" type="text">
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">学校层次：</label>
				<div class="col-sm-8">
		
				  <select class="form-control valid" id="schoolLevel"  name="schoolLevel">
					<option value="0">请选择</option>
					<option value="1">本科</option>
					<option value="2">专科</option>
				  </select>
		
				  <input id="schoolLevelType" class="form-control" type="hidden">
				</div>
			  </div>
		
			  <div class="form-group">
				<label class="col-sm-3 control-label">技能等级证书：</label>
				<div class="col-sm-8">
				  <input id="ratingCertificate" name="ratingCertificate" class="form-control" type="text">
				</div>
			  </div>
		
			</div>
		`)
        } else if (ev.target.value == 1 || ev.target.value == 2) {
            $("#insertion").html(`
			<div class="teacher">
			
				<div class="form-group">
					<label class="col-sm-3 control-label">身份证号码：</label>
					<div class="col-sm-8">
					  <input id="idNumber" name="idNumber" class="form-control" type="text" maxlength="18">
					</div>
			    </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">政治面貌：</label>
				<div class="col-sm-8">
				  <input id="politicalAffiliation" name="politicalAffiliation" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">单位名称：</label>
				<div class="col-sm-8">
				  <input id="unit_school" name="school" class="form-control" type="text">
				</div>
			  </div>
			
<!--			  <div class="form-group">-->
<!--				<label class="col-sm-3 control-label">单位所在地：</label>-->
<!--				<div class="col-sm-8">-->
<!--				  <input id="schoolAddress" name="schoolAddress" class="form-control" type="text">-->
<!--				</div>-->
<!--			  </div>-->
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">详细地址：</label>
				<div class="col-sm-8">
				  <input id="schoolIndetailAddress" name="schoolIndetailAddress" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">所在系部：</label>
				<div class="col-sm-8">
				  <input id="department" name="department" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">所在专业：</label>
				<div class="col-sm-8">
				  <input id="major" name="major" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">职位信息：</label>
				<div class="col-sm-8">
				  <input id="officialCapacity" name="officialCapacity" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">职称信息：</label>
				<div class="col-sm-8">
				  <input id="officialCapacityName" name="officialCapacityName" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				  <label class="col-sm-3 control-label">照片信息：</label>
				  <div class="col-sm-8">
					 <input id="img" name="img" class="form-control" type="hidden">
					 <div class="closeBtn">
						
					 </div>
					 <button type="button" class="btn btn-success" id="btnAdd" style="margin-top: 10px;">
						<i class="fa fa-cloud"></i>图片上传
					 </button>
				  </div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">收件地址：</label>
				<div class="col-sm-8">
				  <input id="shippingAddress" name="shippingAddress" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">收件详细地址：</label>
				<div class="col-sm-8">
				  <input id="shippingIndetailAddress" name="shippingIndetailAddress" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">税号：</label>
				<div class="col-sm-8">
				  <input id="dutyParagraph" name="dutyParagraph" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">税号单位名称：</label>
				<div class="col-sm-8">
				  <input id="ticketOrgName" name="ticketOrgName" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">卡号：</label>
				<div class="col-sm-8">
				  <input id="cardNumber" name="cardNumber" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">帐户名：</label>
				<div class="col-sm-8">
				  <input id="accountName" name="accountName" class="form-control" type="text">
				</div>
			  </div>
			
			  <div class="form-group">
				<label class="col-sm-3 control-label">所属银行：</label>
				<div class="col-sm-8">
				  <input id="bank" name="bank" class="form-control" type="text">
				</div>
			  </div>
			
			</div>
		`)
        }

        layui.use(['upload', 'laydate'], function () {
            var upload = layui.upload, laydate = layui.laydate;

            laydate.render({
                elem: '#timeOfEnrollment'
                , type: 'month'
            });

            upload.render({
                elem: '#btnAdd',
                url: '/common/sysFile/upload',
                accept: 'images', //只允许上传图片
                acceptMime: 'image/*', //只筛选图片
                multiple: true,
                number: 5,
                size: 10240,
                done: function (r) {

                    $(".closeBtn").html(`
					<img id="upImg" src="${r.data}" alt="" width="100" height="100"><span class="iconclose"><img src="../../../img/close.png"></span>
				`);
                    $("#img").val(r.data);

                    $(".iconclose").click(function () {
                        $(".closeBtn").html('');
                        $("#img").val('');
                    })

                },
                error: function (r) {
                    layer.msg(r.msg);
                }
            });
        });

    })
}

